﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using WFNetLib;
using System.Net;
using WFNetLib.Log;
using System.Runtime.InteropServices;

namespace 教室客户端
{
    public partial class Form3 : Form
    {
        // 引用系统钩子
        [DllImport("user32.dll")]
        public static extern IntPtr GetActiveWindow();

        [DllImport("user32.dll")]
        public static extern IntPtr SetActiveWindow(IntPtr hwnd);
        JSON_ExperimentData curEX = null;
        JSON_LoginData LoginData = null;
        public Form3()
        {
            InitializeComponent();
            Form1 f1 = new Form1();
            if (f1.ShowDialog() == DialogResult.OK)
            {
                LoginData = f1.LoginData;
                Form2 f2 = new Form2(LoginData.Experiments);
                if (f2.ShowDialog() == DialogResult.OK)
                {
                    curEX = f2.curEX;
                }
                else
                    curEX = null;
            }
            else
                curEX = null;
        }
        private void Form3_Load(object sender, EventArgs e)
        {
            
            if (curEX == null || LoginData == null)
            {
                this.Close();
                return;
            }
            notifyIcon1.Icon = this.Icon;
            notifyIcon1.Visible = false;
            notifyIcon1.Text = this.Text;
            notifyIcon1.ContextMenuStrip = contextMenuStrip1;//托盘菜单项在图标右键时显示              
            //notifyIcon1.Click += new EventHandler(this.nIcon_Click);//委托点击事件 

            textBox1.Text = LoginData.Teacher.Name;
            textBox2.Text = curEX.Name;
            textBox3.Text = curEX.Room;
            listBox1.Items.Clear();
            foreach (JSON_ExperimentTime et in curEX.Times)
            {
                string t1;
                t1 = et.StartTime.ToString().Insert(2, ":");
                t1 = t1+"～"+et.EndTime.ToString().Insert(2, ":");
                listBox1.Items.Add(t1);
            }
            checkBox8.Checked = Properties.Settings.Default.bHuDong;
            if(curEX.Week1)
                checkBox1.Checked = true;
            if (curEX.Week2)
                checkBox2.Checked = true;
            if (curEX.Week3)
                checkBox3.Checked = true;
            if (curEX.Week4)
                checkBox4.Checked = true;
            if (curEX.Week5)
                checkBox5.Checked = true;
            if (curEX.Week6)
                checkBox6.Checked = true;
            if (curEX.Week7)
                checkBox7.Checked = true;
            string log;
            log = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss--->" + "教师：" + LoginData.Teacher.Name + "登陆无线评价系统");
            TextLog.AddTextLog(log);
            log = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss--->" + "选择的课程内容为：" + curEX.Name);
            TextLog.AddTextLog(log);
            log = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss--->" + "所在教室：" + curEX.Room);
            TextLog.AddTextLog(log);
            MyCOM.PortName = Properties.Settings.Default.Com;//ConfigurationManager.AppSettings["Com"];
            while (true)
            {
                try
                {
                    MyCOM.Open();
                    ShowText("串口打开，无线评价服务已启动");
                    break;
                }
                catch
                {                    
                    if(MessageBox.Show("指定串口" + MyCOM.PortName + "无法打开,请检查后重试!","错误",MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)==DialogResult.Cancel)
                    {
                        curEX = null;
                        this.Close();
                        return;
                    }
                }
            }
            try
            {
                WFHttpWebResponse WebResponse = new WFHttpWebResponse();
                string url = "http://wxpj.hrbeu.edu.cn/webAPI/API_Submit.aspx";
                HttpWebResponse hr = WebResponse.CreateGetHttpResponse(url);
            }
            catch// (System.Exception ex)
            {
            	
            }            
        }
        byte[] COMRx = new byte[11];
        int COMRxCount = 0;
        Form5 f5 = null;           
            
        private void MyCOM_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int count = MyCOM.BytesToRead;
            while (count != 0)
            {
                try
                {                    
                    byte rx = (byte)MyCOM.ReadByte();
                    count--;
                    COMRx[COMRxCount++] = rx;
                    if (COMRxCount == 1)
                    {
                        if (COMRx[0] != 0x16)
                        {
                            COMRxCount = 0;
                        }
                    }
                    else if (COMRxCount == 2)
                    {
                        if (COMRx[1] != 0x16)
                        {
                            COMRxCount = 0;
                        }
                    }
                    else if (COMRxCount == 3)//命令
                    {
                        if (COMRx[2] != 0x01 && COMRx[2] != 0x02 && COMRx[2] != 0x03)
                        {
                            COMRxCount = 0;
                        }
                    }
                    else if (COMRxCount == 4)//长度
                    {
                        if (COMRx[3] != 5)
                        {
                            COMRxCount = 0;
                        }
                    }
                    else if (COMRxCount > 4)//判断是否接收完成
                    {
                        if (COMRxCount == 11 && COMRx[10] == 0x0d)//正确完成
                        {
                            if (Verify.GetVerify_byteSum(COMRx, 0, 9) == COMRx[9])//校验正确
                            {
                                //textBox1.Text = byteToHexStr(COMRx, " ");
                                byte[] Tx = new byte[7];
                                Tx[0] = 0x16;
                                Tx[1] = 0x16;
                                Tx[2] = COMRx[2];
                                Tx[3] = 0x01;
                                if (COMRx[2] == 0x01)
                                {
                                    ShowText("座位号" + BytesOP.BCD2Byte(COMRx[6]).ToString() + "进行教师评价");
                                }
                                else if (COMRx[2] == 0x02)
                                {
                                    ShowText("座位号" + BytesOP.BCD2Byte(COMRx[6]).ToString() + "进行课程评价");
                                }
                                else if (COMRx[2] == 0x03)
                                {
                                    ShowText("座位号" + BytesOP.BCD2Byte(COMRx[6]).ToString() + "进行课堂互动");
                                    if(checkBox8.Checked)
                                    {
                                        this.Invoke((EventHandler)(delegate
                                        {
                                            if (f5 == null) //如果子窗体为空则创造实例 并显示
                                            {
                                                f5 = new Form5();
                                                IntPtr activeForm = GetActiveWindow(); // 先得到当前的活动窗体 
                                                f5.Show(); // 弹出新窗体
                                                SetActiveWindow(activeForm); // 在把焦点还给之前的活动窗体
                                                f5.ExternAddNum(COMRx[8]);
                                            }
                                            else
                                            {
                                                if (f5.IsDisposed)//若子窗体关闭 则打开新子窗体 并显示
                                                {
                                                    f5 = new Form5();
                                                    IntPtr activeForm = GetActiveWindow(); // 先得到当前的活动窗体 
                                                    f5.Show(); // 弹出新窗体
                                                    SetActiveWindow(activeForm); // 在把焦点还给之前的活动窗体
                                                    f5.ExternAddNum(COMRx[8]);
                                                }
                                                else
                                                {
                                                    f5.ExternAddNum(COMRx[8]);
                                                }
                                            }
                                        }));

                                    }
                                }
                                if (COMRx[2] == 0x01 || COMRx[2] == 0x02)
                                {
                                    /************************************************************************/
                                    /* 向服务器提交                                                         */
                                    /************************************************************************/
                                    WFHttpWebResponse WebResponse = new WFHttpWebResponse();
                                    string url = "http://wxpj.hrbeu.edu.cn/webAPI/API_Submit.aspx?uid=";
                                    url += LoginData.Teacher.ID.ToString();
                                    url += "&eid=";
                                    url += curEX.ID.ToString();
                                    url += "&type=";
                                    url += COMRx[2].ToString();
                                    url += "&ZuoHao=";
                                    url += BytesOP.BCD2Byte(COMRx[6]).ToString();
                                    url += "&grade=";
                                    url += COMRx[8].ToString();
                                    try
                                    {
                                        HttpWebResponse hr = WebResponse.CreateGetHttpResponse(url);
                                        string ret = WebResponse.Content;
                                        JSON_SubmitData SD = JsonSerializeHelper.DeSerialize<JSON_SubmitData>(ret);
                                        ShowText("返回结课为----" + SD.message + "----");
                                        Tx[4] = (byte)SD.errIndex;
                                    }
                                    catch (System.Exception ex)
                                    {
                                        ShowText("返回结课为----未知错误----:" + ex.Message);
                                        Tx[4] = 0x03;
                                    }
                                }
                                else
                                    Tx[4] = 0x01;
                                Tx[5] = Verify.GetVerify_byteSum(Tx, 0, 5);
                                Tx[6] = 0x0d;
                                MyCOM.Write(Tx, 0, 7);
                                //textBox2.Text = byteToHexStr(Tx, " ");
                            }
                            COMRxCount = 0;
                        }
                        else
                        {
                            if (COMRxCount > 10)
                            {
                                COMRxCount = 0;
                            }
                        }
                    }                    
                }
                catch
                {

                }
            }
        }
        private delegate void ShowTextLog(string str);
        private void ShowTextLogProc(string str)
        {
            if (textBox4.Text.Length > 20000)
                textBox4.Clear();
            str = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "--->" + str;
            textBox4.AppendText(str + "\r\n");
            TextLog.AddTextLog(str);
        }
        public void ShowText(string str)
        {
            this.Invoke(new ShowTextLog(ShowTextLogProc), str);
        }
        private void Form3_FormClosing(object sender, FormClosingEventArgs e)
        {
//             if(MessageBox.Show("确认退出吗？\n退出后本实验室无线评价系统将无法工作!!!!!!","警告",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)==DialogResult.No)
//                 e.Cancel = true;
            if (curEX == null || LoginData == null)
            {
                return;
            }
            e.Cancel = true; // 取消关闭窗体 
            this.Hide();
            this.ShowInTaskbar = false;//取消窗体在任务栏的显示 
            this.notifyIcon1.Visible = true;//显示托盘图标
            this.notifyIcon1.ShowBalloonTip(0x2710, "系统托盘提示", "无线评价系统在后台继续运行。", ToolTipIcon.Info);//托盘图标加载时提示
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form4 f = new Form4(LoginData.Teacher.ID);
            f.ShowDialog();
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Show();
                this.ShowInTaskbar = true;
                this.notifyIcon1.Visible = false;
            }
        }

        private void 显示无线评价客户端ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.ShowInTaskbar = true;
            this.notifyIcon1.Visible = false;
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认退出吗？\n退出后本实验室无线评价系统将无法工作!!!!!!", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                this.Dispose(true);
                Application.ExitThread();
            }
        }

        private void Form3_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮 
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.ShowInTaskbar = false;//取消窗体在任务栏的显示 
                this.notifyIcon1.Visible = true;//显示托盘图标
                this.notifyIcon1.ShowBalloonTip(0x2710, "系统托盘提示", "无线评价系统在后台继续运行。", ToolTipIcon.Info);//托盘图标加载时提示
            }
        }

        private void checkBox8_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.bHuDong = checkBox8.Checked;
            Properties.Settings.Default.Save();
        }
    }
}
